<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:include="include :: header"></head>
<body class="hold-transition skin-blue sidebar-mini">
<!--编辑模态框-->
<div class="modal fade" id="modal-edit">
    <div class="modal-dialog" style="width:300px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">编辑</h4>
            </div>
            <form id="edit-form" class="form-horizontal">
                <div class="modal-header ">
                    <input name="id" type="hidden" style="display: none"  />
                    <input name="priceType" type="hidden"/>
                    <div class="col-md-12">
                        <div class="form-group">
                            <label class="control-label">单价:</label>
                            <label class="control-label">
                                <input name="price" type="number" class="form-control" min="0" max="210000000" step="0.01" />
                            </label>
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-info file-contract btn-file" id="btn-save-edit">保存</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!--导入-->
<div class="modal fade" id="modal-import">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Excel信息导入</h4>
            </div>
            <div class="modal-body">
                <form id="importForm">
                    <div class="form-group">
                        <label>模版</label>
                        <a th:href="@{/file/随机备件计划模板.xlsx}">点击下载</a>
                    </div>
                    <div class="form-group">
                        <label>上次导入错误数据</label>
                        <a id="download-error"
                           th:data-url="@{/files/{user}/errorAsp.xlsx(user=${session.user.account})}"
                           href="javascript:void(0);">点击下载</a>
                    </div>
                    <div class="form-group">
                        <label>选择Excel文件并上传</label>
                        <input class="btn" type="file" multiple="multiple" name="file">
                        <p class="help-block">请按模板格式进行导入，信息与模板信息对应。</p>
                        <input type="hidden" style="display: none" name="batId" th:value="${batId}"/>
                        <input type="hidden" style="display: none" name="id" th:value="${cost.id}"/>
                        <input type="hidden" style="display: none" name="part" value="随机备件"/>
                        <input type="hidden" style="display: none" name="proCode" th:value="${project.code}"/>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button id="btn-upload" type="button" class="btn btn-success">
                    <span class="Bold">上传</span>
                </button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>
<section class="content-header">
    <h1 style="display: inline-block">随机备件计划列表</h1>
<!--    <a th:if="${mode=='edit'}" th:href="@{'/getData/accountingCostEdit/'}+${batId}+'/'+${project.code}" type="button" class="btn btn-success"-->
<!--       style="text-align:center;vertical-align:middle;font-size:30px;position:absolute;right:3%;display: inline-block;background-color: transparent;border: none;color: #5c5c5c;outline:none;">-->
<!--        <i style="-moz-transform:scaleX(-1);-webkit-transform:scaleX(-1);-o-transform:scaleX(-1);transform:scaleX(-1);filter:FlipH;"-->
<!--           class="glyphicon glyphicon-share-alt"></i><span-->
<!--            style="margin-left: 5px;font-size: 16px;position: absolute;top: 20%;">返回</span>-->
<!--    </a>-->
    <a th:if="${mode!='edit' && mode!='seeEst'}" href="javascript:window.history.back();" type="button" class="btn btn-success"
       style="text-align:center;vertical-align:middle;font-size:30px;position:absolute;right:3%;display: inline-block;background-color: transparent;border: none;color: #5c5c5c;outline:none;">
        <i style="-moz-transform:scaleX(-1);-webkit-transform:scaleX(-1);-o-transform:scaleX(-1);transform:scaleX(-1);filter:FlipH;"
           class="glyphicon glyphicon-share-alt"></i><span
            style="margin-left: 5px;font-size: 16px;position: absolute;top: 20%;">返回</span>
    </a>
</section>
<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="box">
                <div class="box-header">
                    <div class="row">
                        <div class="form-inline" style="border-bottom: 3px #D2D6DE solid;">
                            <div class="form-group">
                                <label class="control-label">
                                    项目编号：
                                </label>
                                <label class="control-label" th:text="${project.code}"></label>
                                <input id="code" type="hidden" th:value="${project.code}" style="display: none">
                            </div>
                            <div class="form-group">
                                <label class="control-label">
                                    项目名称：
                                </label>
                                <label class="control-label" th:text="${project.name}"></label>
                            </div>
                            <div class="form-group">
                                <label class="control-label">
                                    需方：
                                </label>
                                <label class="control-label" th:text="${project.demander}"></label>
                            </div>
                            <div class="form-group">
                                <label class="control-label">
                                    安装地点：
                                </label>
                                <label class="control-label" th:text="${project.address}"></label>
                            </div>
                            <div class="form-group">
                                <label class="control-label">
                                    项目数量：
                                </label>
                                <label class="control-label" th:text="${project.num}"></label>
                            </div>
                            <div class="form-group">
                                <label class="control-label">
                                    设计类别：
                                </label>
                                <label class="control-label"
                                       th:text="${project.projectClassify == 1 ? '设计':'非设计'}"></label>
                            </div>
                            <div class="form-group pull-right">
                                <label id="finishStatus" th:if="${cost.finishStatus eq 1}" class="badge label-default">未完结</label>
                                <label id="finishStatus" th:if="${cost.finishStatus eq 2}" class="badge label-warning">执行中</label>
                                <label id="finishStatus" th:if="${cost.finishStatus eq 3}" class="badge label-success">完结</label>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-12">
                        <form id="queryForm" class="form-horizontal">
                            <input type="hidden" style="display: none" name="finishStatus"
                                   th:value="${cost.finishStatus}"/>
                            <input type="hidden" style="display: none" name="batId" th:value="${batId}"/>
                            <input type="hidden" style="display: none" name="id" th:value="${cost.id}"/>
                            <input type="hidden" style="display: none" name="proCode" th:value="${project.code}"/>
                            <input type="hidden" style="display: none" name="part" value="随机备件"/>
                            <input type="hidden" style="display: none" name="major" th:value="${cost.major}" />
                            <input type="hidden" style="display: none" name="displayMode" value="source"/>
                            <div class="row">
                                <div class="form-inline">
                                    <div class="form-group" style="padding-right: 10px;">
                                        <label class="control-label">
                                            提报计划物料描述：
                                        </label>
                                        <label class="control-label">
                                            <input name="matDesc" class="form-control" type="text"/>
                                        </label>
                                    </div>
<!--                                    <div class="form-group" style="padding-right: 10px;">-->
<!--                                        <label class="control-label">-->
<!--                                            部分：-->
<!--                                        </label>-->
<!--                                        <label class="control-label">-->
<!--                                            <input name="part" class="form-control" type="text"/>-->
<!--                                        </label>-->
<!--                                    </div>-->
                                    <div class="form-group" style="padding-right: 10px;">
                                        <label class="control-label">
                                            金额来源：
                                        </label>
                                        <label class="control-label">
                                            <select name="priceType" class="form-control">
                                                <option value="">请选择</option>
                                                <option value="1">系统获取</option>
                                                <option value="2">人工编辑</option>
                                            </select>
                                        </label>
                                    </div>
                                    <div class="form-group pull-right">
                                        <label class="control-label">
                                            <button id="btn-search" style="margin-top: 4px" type="button" class="btn btn-success">搜索</button>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                </div>
                <div id="toolBar" class="row">
                    <div class="form-group pull-left" style="margin-right: 10px" th:if="${mode=='edit'}">
                        <button shiro:hasPermission="ver:detail:edit" id="btn-calculationFinish" th:if="${cost.finishStatus != null && (cost.finishStatus eq 1 || cost.finishStatus eq 2)}" class="btn btn-success">计算并完结</button>
                        <button shiro:hasPermission="ver:detail:edit" id="btn-cancelFinish" th:if="${cost.finishStatus != null && cost.finishStatus eq 3}" class="btn btn-warning">取消完结</button>
                    </div>
                    <div class="form-group pull-left" style="margin-left: 10px">
                        <label class="control-label">
                            税率：
                        </label>
                        <label class="control-label">
                            <input id="input_tax" readonly="readonly"
                                   style="display: inline-block;

                                   border: none;
                                   box-shadow: 2px 2px 5px #343434 inset;
                                   border-radius: 5px;
                                   outline:none;
                                   text-align: center;
                                   line-height: 36px;"
                                   type="text" maxlength="255" th:value="${tax}"/>
                        </label>
                    </div>
                    <div class="form-group pull-left" style="margin-left: 10px">
                        <label class="control-label">
                            总金额（不含税）：
                        </label>
                        <label class="control-label">
                            <input id="input_amount" readonly="readonly"
                                   style="display: inline-block;

                                   border: none;
                                   box-shadow: 2px 2px 5px #343434 inset;
                                   border-radius: 5px;
                                   outline:none;
                                   text-align: center;
                                   line-height: 36px;"
                                   type="text" maxlength="255" th:value="${totalPrice}"/>
                        </label>
                        <label class="control-label">
                            <span>元</span>
                        </label>
                    </div>
                    <div class="form-group pull-left" style="margin-left: 10px">
                        <label class="control-label">
                            总金额（含税）：
                        </label>
                        <label class="control-label">
                            <input id="input_tax_amount" readonly="readonly"
                                   style="display: inline-block;
                                   border: none;
                                   box-shadow: 2px 2px 5px #343434 inset;
                                   border-radius: 5px;
                                   outline:none;
                                   text-align: center;
                                   line-height: 36px;"
                                   type="text" maxlength="255" th:value="${totalPriceHaveTax}"/>
                        </label>
                        <label class="control-label">
                            <span>元</span>
                        </label>
                    </div>
                    <div class="form-group pull-left" style="margin-left: 10px">
                        <label class="control-label">
                            成本项总金额：
                        </label>
                        <label class="control-label">
                            <input id="input_cost_totalPrice" readonly="readonly"
                                   style="display: inline-block;
                                   border: none;
                                   box-shadow: 2px 2px 5px #343434 inset;
                                   border-radius: 5px;
                                   outline:none;
                                   text-align: center;
                                   line-height: 36px;"
                                   type="text" maxlength="255" th:value="${cost.totalPrice == null?0:cost.totalPrice}"/>
                        </label>
                        <label class="control-label">
                            <span>元</span>
                        </label>
                    </div>
                    <div class="form-group pull-left" style="margin-left: 10px">
                        <button id="btn-source" class="btn btn-success">原数据模式</button>
                        <button id="btn-single" class="btn btn-default">单项目模式</button>
                    </div>
<!--                    <div class="form-group pull-left" style="margin-left: 10px" th:if="${mode=='edit'}">-->
<!--                        <button shiro:hasPermission="ver:detail:edit" id="btn-import" th:if="${cost.finishStatus != null && (cost.finishStatus eq 1 || cost.finishStatus eq 2)}" class="btn btn-success">导入历史数据</button>-->
<!--                    </div>-->
                </div>
                <div class="box-body">
                    <table id="bootstrap-table"></table>
                </div>
            </div>
        </div>
    </div>
</section>

<div th:include="include :: footer"></div>

<script th:inline="javascript">
    let table;
    /**
     * 去掉小数点后面多余的0
     * @param number
     * @returns {number}
     */
    function dealingWithDecimals(number){
        return parseFloat(number);
    }
    $(function () {
        $(window).bind('beforeunload', function () {
            window.opener.loadCostSheet();
        });
        $("#input_amount").val(dealingWithDecimals($("#input_amount").val()));
        $("#input_tax_amount").val(dealingWithDecimals($("#input_tax_amount").val()));
        $("#input_cost_totalPrice").val(dealingWithDecimals($("#input_cost_totalPrice").val()));
        //加载参数
        initParam();
        //加载外购件数据
        initItemList();
        //搜索
        $("#btn-search").on('click',function (e){
           js.table.refresh(table)
        });
        /**
         * 模态框隐藏事件， 重置表单，重置验证
         */
        js.modal.hideEvent("modal-edit", function () {
            // js.validate.reset("halfAdjEditForm");
            js.reset("edit-form");
        });
        initItemList();
        /**
         * 原数据模式
         */
        $("#btn-source").on('click', function () {
            $("#btn-source").attr("class", "btn btn-success");
            $("#btn-single").attr("class", "btn btn-default");
            $("#queryForm [name='displayMode']").val("source");
            js.table.refresh(table)
        });
        /**
         * 单项目模式
         */
        $("#btn-single").on('click', function () {
            $("#btn-single").attr("class", "btn btn-success");
            $("#btn-source").attr("class", "btn btn-default");
            $("#queryForm [name='displayMode']").val("single");
            js.table.refresh(table)
        });
        /** 验证 */
        js.validate.init("edit-form", {
            fields: {
                price: {
                    validators: {
                        notEmpty: {message: '请输入单价'}
                    }
                }
            }
        });
        /**
         * 保存编辑
         * */
        $("#btn-save-edit").on('click',function (e){
            $("#edit-form [name='priceType']").val(2);
            js.validSubmit({
                formId: "edit-form",
                url: ctx + "accountingInfo/saveEdit",
                data: new FormData($("#edit-form")[0]),
                success: function (result) {
                    if (result.type === web_status.SUCCESS) {
                        js.modal.success(result.msg);
                        js.table.refresh(table);
                        js.modal.hide('modal-edit');
                    }else{
                        s.modal.warning(result.msg);
                    }
                    js.modal.closeLoading();
                },
                error: function () {
                    s.modal.warning(result.msg);
                    js.modal.closeLoading();
                }
            });
        })


        /**
         * 计算完结
         * */
        $("#btn-calculationFinish").on("click", function(e){
            js.post({
                url: ctx + 'accountingInfo/automaticCalculationPur',
                type: 'post',
                traditional: true,            // 阻止深度序列化， 使参数可以使用数组
                dataType: 'json',
                contentType: "application/x-www-form-urlencoded",
                data: $("#queryForm").serialize(),
                async: true,                // 异步执行
                success: function (result) {
                    if (result.type === web_status.SUCCESS) {

                        if(result.data.busBudgetAccountingCost.finishStatus===3){
                            $("#finishStatus").attr("class","badge label-success");
                            $("#finishStatus").text("完结");
                            window.opener.loadCostSheet();
                            location.reload();
                        }
                    }
                },
                error: function () {
                    js.modal.fail();
                }
            });
        })

        /**
         * 取消完结
         * */
        $("#btn-cancelFinish").on("click", function (e) {
            js.post({
                url: ctx + 'accountingInfo/cancelCalculationFinishRawMaterial',
                type: 'post',
                traditional: true,            // 阻止深度序列化， 使参数可以使用数组
                dataType: 'json',
                contentType: "application/x-www-form-urlencoded",
                data: $("#queryForm").serialize(),
                async: true,                // 异步执行
                success: function (result) {
                    if (result.type === web_status.SUCCESS) {
                        if (result.data.busBudgetAccountingCost.finishStatus === 2) {
                            $("#finishStatus").attr("class", "badge label-warning");
                            $("#finishStatus").text("执行中");
                            window.opener.loadCostSheet();
                            location.reload();
                        }
                    }
                },
                error: function () {
                    js.modal.fail();
                }
            });
        });
        /** 导入表单验证 */
        js.validate.init("importForm", {
            fields: {
                file: {
                    validators: {
                        notEmpty: {message: '上传文件不能为空'},
                        file: {extension: 'xls,xlsx', message: '请选择excel文件'}
                    }
                }
            }
        });
        /**
         * 打开导入模态框
         * */
        $("#btn-import").on("click",function (){
            js.modal.open("modal-import");
        });

        /** 导入模态框隐藏事件 */
        js.modal.hideEvent("modal-import", function () {
            js.validate.reset("importForm");
            $("#importForm [name='file']").val(null);
        });
        /** 导入计划 */
        $("#btn-upload").click(function () {
            js.modal.confirm("尊敬的用户，导入数据会导致当前表数据被清空，您确认要继续导入数据吗？",function (){
                var $this = $(this);
                $this.attr('disabled', true);
                js.validSubmit({
                    formId: "importForm",
                    url: ctx + "accountingInfo/accompanyingSparePartsImport",
                    data: new FormData($("#importForm")[0]),
                    success: function (result) {
                        if (result.type === web_status.SUCCESS) {
                            js.modal.alert(result.msg);
                            if (result.msg == '导入完成') {
                                js.modal.hide("modal-import");
                            }
                            js.table.refresh(table);
                            $this.attr('disabled', false);
                        }
                    }
                });
            })
        });
    });

    /**
     * 加载参数
     */
    function initParam() {
        //获取税率
        js.post({
            url: ctx + 'accountingInfo/getTax',
            type: 'post',
            traditional: true,            // 阻止深度序列化， 使参数可以使用数组
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            data: {
                batId: $("#queryForm [name='batId']").val()
            },
            async: true,                // 异步执行
            success: function (result) {
                if (result.type === web_status.SUCCESS) {
                    $("#input_tax").val(result.data.value+"%");
                }
            },
            error: function () {
                js.modal.fail();
            }
        });
    }

    /**
     * 加载列表数据
     */
    function initItemList() {

        table = js.table.init({
            id: "bootstrap-table",
            queryForm: 'queryForm',
            url: ctx + "accountingInfo/purList",
            showColumns: true,
            showExport: true,
            pagination: true,                                   // 是否显示分页
            toolbar:'#toolBar',
            uniqueId: "id",
            columns: [
                {
                    title: '序号', field: 'id', width: '60',
                    formatter: function (value, row, index) {
                        return index + 1;
                    }
                },
                {title: '部分', field: 'part', width: '120'},
                // {title: '专业', field: 'major'},
                {title: '提报计划物料描述', field: 'matDesc', width: '200'},
                {title: '实用数量', field: 'num'},
                {title: '单位', field: 'unit', width: '50'},
                {title: '型号/标准号', field: 'standardNo'},
                {title: '品牌', field: 'brand'},
                {title: '备注', field: 'remark'},
                {title: 'SAP物料编码', field: 'sapCode', width: '95'},
                {title: '采购物料描述', field: 'buyMatDesc', width: '200'},
                {title: '单价', field: 'price'},
                {
                    title: '总价',
                    formatter: function (value, row, index) {
                        return (row.price * row.num).toFixed(2);
                    }
                },
                {
                    title: '金额来源', field: 'priceType', width: '65',
                    formatter: function (value, row, index) {
                        if (value === 1) {
                            return '<label class="badge label-success">系统获取</label>';
                        } else if (value === 2) {
                            return '<label class="badge label-warning">人工编辑</label>';
                        }
                    }
                },
                {
                    title: '操作', width: 70,
                    formatter: function (value, row, index) {
                        let elements = new Array();
                        let finishStatus = $("#queryForm [name='finishStatus']").val();
                        let mode = $("#mode").val();
                        if(hasP('ver:detail:edit')) {
                            if (mode === 'edit' && finishStatus != 3) {
                                elements.push('<button style="width: 48px" class="btn btn-warning btn-xs" onclick="showEditPanel(' + row.id + ')">编辑</button>');
                            }
                        }
                        return elements.join('');
                    }
                }

            ]
        });
        /** 下载导入失败excel */
        $("#download-error").click(function () {
            var that = $(this);
            js.post({
                url: ctx + "accountingInfo/exist",
                async: false,
                data: {
                    url: that.attr("data-url")
                },
                success: function (result) {
                    if (result.type === web_status.SUCCESS) {
                        that.attr("href", that.attr("data-url") + "?timeStamp=" + new Date().getTime());
                    } else {
                        js.modal.warning("没有需要处理的文件");
                    }
                }
            });
        });
    }

    /**
     * 打开编辑面板
     */
    function showEditPanel(id){
        let rowData = $('#bootstrap-table').bootstrapTable('getRowByUniqueId', id);
        $("#edit-form").fillData(rowData);
        js.modal.open('modal-edit');
    }
</script>
</body>
</html>